﻿package net.wangit.dev.table;

import java.util.List;

import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.framework.config.DomainsSettings;
import net.wangit.jdbc.DBFactory;
import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.database.Database;
import net.wangit.jdbc.table.Column;
import net.wangit.jdbc.table.PrimaryKey;
import net.wangit.jdbc.table.TableMeta;
import net.wangit.jdbc.table.TableMetaFactory;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;


public class CreateTableUI implements UnitInterceptor {

	public CreateTableUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String tableName = ActionContextHelper.getRequest2Session(ac,
				"tablename", TableUI.KEY, null);
		if (!unit.getShowMode().equals("a") && !Checker.isEmpty(tableName)) {
			String domain = ConsoleDomainUtil.getDomain(ac);
			DBImplementor actionDB = (DBImplementor) DBFactory
					.getDB(DomainsSettings.getDatasource(domain));
			Database database = actionDB.getJDBCSettings().getDatabase();
			unit.setTitle((new StringBuilder(String.valueOf(unit.getTitle())))
					.append(" [ ").append(database.getName()).append(" ]")
					.toString());
			String script = getScript(domain, tableName);
			unit.getElement("script").setDefaultValue(script);
		}
		return unit.write(ac);
	}

	private String getScript(String domain, String tableName) throws Exception {
		try {
			StringBuffer script;
			script = new StringBuffer("create table ");
			script.append(tableName).append(" (");
			DBImplementor actionDB = (DBImplementor) DBFactory
					.getDB(DomainsSettings.getDatasource(domain));
			Database database = actionDB.getJDBCSettings().getDatabase();
			TableMeta meta = TableMetaFactory.getTableMeta(domain, tableName);
			PrimaryKey primaryKey = meta.getPrimaryKey();
			List<Column> primaryKeyColumns = primaryKey.getColumns();
			List<Column> columns = meta.getColumns();
			for (int i = 0; i < columns.size(); i++) {
				Column column = columns.get(i);
				script.append("\n ").append(column.getName()).append(" ")
						.append(column.getType().getSqlTypeName(database));
				if (!column.isNullable() || primaryKeyColumns.contains(column))
					script.append(" NOT NULL");
				script.append(",");
			}
			script.append("\n")
					.append(primaryKey.sqlConstraintString(database)).append(
							"\n)");
			return script.toString();
		} catch (Exception e) {
			return "Could not create script!";
		}
	}
}
